package com.mfangsoft.zhuangjialong.common.utils;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.regex.Pattern;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.ImageIcon;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Element;

import com.mfangsoft.zhuangjialong.common.controller.FileUploadController;
//旧的jpeg处理类
//import com.sun.image.codec.jpeg.*; 
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;

public class ImgUtil {

	    // 二维码尺寸  
	    private static final int QRCODE_SIZE = 430;  
	    // LOGO宽度  
	    private static final int WIDTH = 180;  
	    // LOGO高度  
	    private static final int HEIGHT = 180;  
	    //透明化色差
	    public static final int COLOR_RANGE = 210;  
	    
	/**
	 * 判断是否图片
	 * 
	 * @param fileName
	 *            文件名或文件路径
	 * @return boolean
	 */
	public static boolean isExpectImg(String fileName) {

		if (StringUtils.isEmpty(fileName)) {
			return false;
		}
		String endStr = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		if ("gif,jpg,jpeg,png,bmp".contains(endStr)) {
			return true;
		} else {
			return false;
		}
	}

	public static String saveBase64Img(String imgBase64){
		String  savePath = PropUtis.getValue(PropUtis.FILE_PATH) + "/" +DateUtils.formatDateYmd(new Date());
		System.out.println("savePath=-----------------------" + savePath);
		String filePath = "";
		try {
			byte[] imgByte = Base64.decode(imgBase64);
			for (int i = 0; i < imgByte.length; ++i) {
				if (imgByte[i] < 0) {// 调整异常数据
					imgByte[i] += 256;
				}
			}
			/*File forder = new File(savePath);
			if (!forder.exists()) {
				forder.mkdirs();
			}
			if (!forder.exists()) {
				throw new RuntimeException("图片文件夹不存在");
			}*/
			Random random = new Random();
			filePath = "/" + DateUtils.formatDateNospace(new Date())+ "-"+ random.nextInt(10) + random.nextInt(10)
					+ random.nextInt(10) + ".jpg";
			/*System.out.println("filePath=-----------------------" + filePath);
			OutputStream out = new FileOutputStream(savePath + filePath);
			System.out.println("outpath=-----------------------" + savePath + filePath);
			out.write(imgByte);
			out.flush();
			out.close();*/
			FileUploadController.httpClientUploadFileBase64(imgByte, savePath, filePath);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		System.out.println("rturnPath=-----------------------" + PropUtis.getValue(PropUtis.FILE_URL)  + "/" + DateUtils.formatDateYmd(new Date()) + filePath);
		return PropUtis.getValue(PropUtis.FILE_URL)  + "/" + DateUtils.formatDateYmd(new Date()) + filePath;
	}

	/**
	 * 
	 * @param f
	 *            图片所在的文件夹路径
	 * @param file
	 *            图片路径
	 * @param ext
	 *            扩展名
	 * @param n
	 *            图片名
	 * @param w
	 *            目标宽
	 * @param h
	 *            目标高
	 * @param per
	 *            百分比
	 */
	private static void Tosmallerpic(String f, File file, String ext, String n, int w, int h, float per) {
		Image src;
		try {
			src = javax.imageio.ImageIO.read(file); // 构造Image对象

			String img_midname = f + n.substring(0, n.indexOf(".")) + ext + n.substring(n.indexOf("."));// 文件保存路径
			int old_w = src.getWidth(null); // 得到源图宽
			int old_h = src.getHeight(null);
			int new_w = 0;
			int new_h = 0; // 得到源图长

			double w2 = (old_w * 1.00) / (w * 1.00);
			double h2 = (old_h * 1.00) / (h * 1.00);

			// 图片跟据长宽留白，成一个正方形图。
			// BufferedImage oldpic;
			// if (old_w > old_h) {
			// oldpic = new BufferedImage(old_w, old_w,
			// BufferedImage.TYPE_INT_RGB);
			// } else {
			// if (old_w < old_h) {
			// oldpic = new BufferedImage(old_h, old_h,
			// BufferedImage.TYPE_INT_RGB);
			// } else {
			// oldpic = new BufferedImage(old_w, old_h,
			// BufferedImage.TYPE_INT_RGB);
			// }
			// }
			// Graphics2D g = oldpic.createGraphics();
			// g.setColor(Color.white);
			// if (old_w > old_h) {
			// g.fillRect(0, 0, old_w, old_w);
			// g.drawImage(src, 0, (old_w - old_h) / 2, old_w, old_h,
			// Color.white, null);
			// } else {
			// if (old_w < old_h) {
			// g.fillRect(0, 0, old_h, old_h);
			// g.drawImage(src, (old_h - old_w) / 2, 0, old_w, old_h,
			// Color.white, null);
			// } else {
			// // g.fillRect(0,0,old_h,old_h);
			// g.drawImage(src.getScaledInstance(old_w, old_h,
			// Image.SCALE_SMOOTH), 0, 0, null);
			// }
			// }
			// g.dispose();
			// src = oldpic;
			// 图片调整为方形结束
			if (old_w > w)
				new_w = (int) Math.round(old_w / w2);
			else
				new_w = old_w;
			if (old_h > h)
				new_h = (int) Math.round(old_h / h2);// 计算新图长宽
			else
				new_h = old_h;
			BufferedImage image_to_save = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
			image_to_save.getGraphics().drawImage(src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null);
			FileOutputStream fos = new FileOutputStream(img_midname); // 输出到文件流

			// 旧的使用 jpeg classes进行处理的方法
			// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
			// JPEGEncodeParam jep =
			// JPEGCodec.getDefaultJPEGEncodeParam(image_to_save);
			/* 压缩质量 */
			// jep.setQuality(per, true);
			// encoder.encode(image_to_save, jep);

			// 新的方法
			saveAsJPEG(100, image_to_save, per, fos);

			fos.close();
		} catch (IOException ex) {
			ex.printStackTrace();
			throw new RuntimeException();
		}
	}

	/**
	 * 以JPEG编码保存图片
	 * 
	 * @param dpi
	 *            分辨率
	 * @param image_to_save
	 *            要处理的图像图片
	 * @param JPEGcompression
	 *            压缩比
	 * @param fos
	 *            文件输出流
	 * @throws IOException
	 */
	public static void saveAsJPEG(Integer dpi, BufferedImage image_to_save, float JPEGcompression,
			FileOutputStream fos) {
		try {
			// useful documentation at
			// http://docs.oracle.com/javase/7/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html
			// useful example program at
			// http://johnbokma.com/java/obtaining-image-metadata.html to output
			// JPEG data

			// old jpeg class
			// com.sun.image.codec.jpeg.JPEGImageEncoder jpegEncoder =
			// com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(fos);
			// com.sun.image.codec.jpeg.JPEGEncodeParam jpegEncodeParam =
			// jpegEncoder.getDefaultJPEGEncodeParam(image_to_save);

			// Image writer
			JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpg").next();
			ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
			imageWriter.setOutput(ios);
			// and metadata
			IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image_to_save),
					null);

			if (dpi != null && !dpi.equals("")) {

				// old metadata
				// jpegEncodeParam.setDensityUnit(com.sun.image.codec.jpeg.JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
				// jpegEncodeParam.setXDensity(dpi);
				// jpegEncodeParam.setYDensity(dpi);

				// new metadata
				Element tree = (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");
				Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
				jfif.setAttribute("Xdensity", Integer.toString(dpi));
				jfif.setAttribute("Ydensity", Integer.toString(dpi));

			}

			if (JPEGcompression >= 0 && JPEGcompression <= 1f) {

				// old compression
				// jpegEncodeParam.setQuality(JPEGcompression,false);

				// new Compression
				JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
				jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
				jpegParams.setCompressionQuality(JPEGcompression);

			}

			// old write and clean
			// jpegEncoder.encode(image_to_save, jpegEncodeParam);

			// new Write and clean up
			imageWriter.write(imageMetaData, new IIOImage(image_to_save, null, null), null);
			ios.close();
			imageWriter.dispose();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}
	

    /** 
     * 缩小Image，此方法返回源图像按给定宽度、高度限制下缩放后的图像 
     * @param inputImage 
     * @param maxWidth：压缩后宽度 
     * @param maxHeight：压缩后高度 
     * @throws java.io.IOException 
     * return  
     */  
    public static BufferedImage scaleByPercentage(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {  
        //获取原始图像透明度类型  
        int type = inputImage.getColorModel().getTransparency();  
        int width = inputImage.getWidth();  
        int height = inputImage.getHeight();  
        //开启抗锯齿  
        RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);  
        //使用高质量压缩  
        renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);  
        BufferedImage img = new BufferedImage(newWidth, newHeight, type);  
        Graphics2D graphics2d =img.createGraphics();  
        graphics2d.setRenderingHints(renderingHints);          
        graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);  
        graphics2d.dispose();  
        return img;  
    }  
     
      
    /** 
     * 通过网络获取图片 
     * @param url 
     * @return 
     */  
    public static BufferedImage getUrlByBufferedImage(String url){  
        try {  
   URL urlObj = new URL(url);    
   HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();    
   // 连接超时    
   conn.setDoInput(true);    
   conn.setDoOutput(true);    
   conn.setConnectTimeout(25000);    
   // 读取超时 --服务器响应比较慢,增大时间    
   conn.setReadTimeout(25000);    
   conn.setRequestMethod("GET");    
   conn.addRequestProperty("Accept-Language", "zh-cn");    
   conn.addRequestProperty("Content-type", "image/jpeg");    
   conn.addRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)");    
   conn.connect();  
            BufferedImage bufImg = ImageIO.read(conn.getInputStream());    
            conn.disconnect();  
            return bufImg;  
        }
    catch (IOException e) {  
   e.printStackTrace();  
    }
        return null;  
    }  
      
    /** 
     * 图片裁剪 
     * @param srcImageFile 图片裁剪地址 
     * @param result 图片输出文件夹 
     * @param destWidth 图片裁剪宽度 
     * @param destHeight 图片裁剪高度 
     * @throws IOException 
     */  
    public final static void cutImage(String srcImageFile, String result, int destWidth, int destHeight) throws IOException {  
            Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
            ImageReader reader = (ImageReader)iterator.next();/*获取图片尺寸*/  
            InputStream inputStream = new FileInputStream(srcImageFile);    
            ImageInputStream iis = ImageIO.createImageInputStream(inputStream);     
            reader.setInput(iis, true);     
            ImageReadParam param = reader.getDefaultReadParam();     
            int imageIndex = 0;
            Rectangle rectangle = new Rectangle((reader.getWidth(imageIndex)-destWidth)/2, (reader.getHeight(imageIndex)-destHeight)/2, destWidth, destHeight); /*指定截取范围*/      
            param.setSourceRegion(rectangle);     
            BufferedImage bi = reader.read(0,param);
            ImageIO.write(bi, "jpg", new File(result));  
    }  
    
    /** 
     * 传入的图像必须是正方形的 才会 圆形  如果是长方形的比例则会变成椭圆的 
     * @param url 用户头像地址   
     * @return 
     * @throws IOException 
     */  
    public static BufferedImage convertCircular(BufferedImage bi1) throws IOException{  
    /*   BufferedImage bi1 = ImageIO.read(new File(url));   */
       //这种是黑色底的  
      // BufferedImage bi2 = new BufferedImage(bi1.getWidth(),bi1.getHeight(),BufferedImage.TYPE_INT_RGB);  
         
     //透明底的图片  
       BufferedImage bi2 = new BufferedImage(bi1.getWidth(),bi1.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);   
       Ellipse2D.Double shape = new Ellipse2D.Double(0,0,bi1.getWidth(),bi1.getHeight());  
       Graphics2D g2 = bi2.createGraphics();  
       g2.setClip(shape);     
       // 使用 setRenderingHint 设置抗锯齿  
       g2.drawImage(bi1,0,0,null);   
       //设置颜色  
       g2.setBackground(new Color(1.0F, 0.75F, 0.0F, 0.45F));  
       g2.dispose();  
       
       return bi2;  
    }  
	
    /** 
     * 图片透明化
     *  
     * @throws Exception 
     */  
    public static BufferedImage hyalinize(BufferedImage bi) throws Exception {  
    	  //图片背景透明化
        ImageIcon imageIcon = new ImageIcon(bi);  
        BufferedImage bufferedImage = new BufferedImage(  
                imageIcon.getIconWidth(), imageIcon.getIconHeight(),  
                BufferedImage.TYPE_4BYTE_ABGR);  
        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();  
        g2D.drawImage(imageIcon.getImage(), 0, 0,  
                imageIcon.getImageObserver());  
        int alpha = 0;  
        for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage  
                .getHeight(); j1++) {  
            for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage  
                    .getWidth(); j2++) {  
                int rgb = bufferedImage.getRGB(j2, j1);  
                if (colorInRange(rgb))  
                    alpha = 0;  
                else  
                    alpha = 255;  
                rgb = (alpha << 24) | (rgb & 0x00ffffff);  
                bufferedImage.setRGB(j2, j1, rgb);  
            }  
        }  
        g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());  
        g2D.dispose(); 
    	return bufferedImage;
    }  
    
    /** 
     * 插入LOGO 
     *  
     * @param source 
     *            二维码图片 
     * @param imgPath 
     *            LOGO图片地址 
     * @param needCompress 
     *            是否压缩 
     * @throws Exception 
     */  
    public static void insertImage(BufferedImage source, Image logo,  
            boolean needCompress) throws Exception {  
    	
    	// 压缩LOGO  
        int width = logo.getWidth(null);  
        int height = logo.getHeight(null);  
        if (needCompress) { 
            if (width > WIDTH) {  
                width = WIDTH;  
            }  
            if (height > HEIGHT) {  
                height = HEIGHT;  
            }  
            Image image = logo.getScaledInstance(width, height,  
                    Image.SCALE_SMOOTH);  
            logo = image;  
        }  
      
        
        // 插入LOGO  
        Graphics2D graphics2d = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;  
        int y = (QRCODE_SIZE - height) / 2;  
        graphics2d.drawImage(logo, x, y, width, height, null);  
        graphics2d.dispose(); 
        
    }  
    
    public static boolean colorInRange(int color) {  
        int red = (color & 0xff0000) >> 16;  
        int green = (color & 0x00ff00) >> 8;  
        int blue = (color & 0x0000ff);  
        if (red >= COLOR_RANGE && green >= COLOR_RANGE && blue >= COLOR_RANGE)  
            return true;  
        return false;  
    }  
  
  
    
    public static Pattern pattern = Pattern.compile("[0-9]*");  
    
	    public static void main(String[] args) {  
	        try {  
	            //图片的本地地址  
        	BufferedImage logo =  getUrlByBufferedImage("http://47.93.78.124/file/upload/2017-07-25/1500965484729.jpg");
        //		            BufferedImage bi =  getUrlByBufferedImage(null);
	            BufferedImage qr =  ImageIO.read(new File("e:/方向陶瓷.jpg"));
	            //处理图片将其压缩成正方形的小图  
	            BufferedImage  convertImage= scaleByPercentage(logo, 180,180);  
	            //裁剪成圆形 （传入的图像必须是正方形的 才会 圆形 如果是长方形的比例则会变成椭圆的）  
	            convertImage = convertCircular(logo);  
	            ImageIO.write(convertImage, "png", new File("E:/logo.png"));  
	            BufferedImage hyalinize = hyalinize(qr);
	            ImageIO.write(hyalinize, "png", new File("E:/qr.png"));  
	            insertImage(hyalinize, convertImage, true);
	            ImageIO.write(hyalinize, "png", new File("E:/003.png"));  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    }  

}
